﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace EstimatesTool.Util;

public static class FileUtil
{
    public static Encoding GetEncoding(string file)
    {
        using var fs = File.OpenRead(file);
        Ude.CharsetDetector cdet = new();
        cdet.Feed(fs);
        cdet.DataEnd();
        var code = cdet.Charset ?? "UTF-8";
        return Encoding.GetEncoding(code);
    }

    public static string LineCompare(List<FileInfo> Files, FileInfo info, out double percentage)
    {
        var list = Files.Where(f => f.Extension.Equals(info.Extension) && !f.FullName.Equals(info.FullName)
            && f.Length >= info.Length * 0.95 && f.Length <= info.Length * 1.05);
        var preList = File.ReadAllLines(info.FullName).Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s));
        int preCount = preList.Count();
        var aftFile = string.Empty;
        percentage = 0;
        foreach (var file in list)
        {
            double aftCount = 0;
            var acfList = File.ReadAllLines(file.FullName).Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s)).ToList();
            foreach (var line in preList)
            {
                var res = acfList.Find(x => x.Equals(line));
                if (res != null) aftCount++;
            }
            var temp = Math.Round(aftCount / preCount * 100, 2);
            if (temp >= 80 && temp > percentage)
            {
                aftFile = file.FullName;
                percentage = temp;
            }
        }
        if (string.IsNullOrEmpty(aftFile)) percentage = 0;
        return aftFile;
    }

    public static bool IsTextFile(string file)
    {
        using var fs = new FileStream(file, FileMode.Open, FileAccess.Read);
        bool isTextFile = true;
        try
        {
            int i = 0;
            int length = (int)fs.Length;
            byte data;
            while (i < length && isTextFile)
            {
                data = (byte)fs.ReadByte();
                isTextFile = (data != 0);
                i++;
            }
            return isTextFile;
        }
        catch
        {
            return false;
        }
    }
}
